package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.config.DroolsConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.opio.util.ExampleBase;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.SysPlan;
import com.ruoyi.system.domain.vo.SysDangerPointVO;
import com.ruoyi.system.domain.vo.SysFirePointVO;
import com.ruoyi.system.domain.vo.SysProductionPointVO;
import com.ruoyi.system.entity.SysDangerPoint;
import com.ruoyi.system.entity.SysEnvironmentPoint;
import com.ruoyi.system.entity.SysFirePoint;
import com.ruoyi.system.entity.SysMonitor;
import com.ruoyi.system.mapper.SysDangerPointMapper;
import com.ruoyi.system.mapper.SysFirePointMapper;
import com.ruoyi.system.service.SysFirePointService;
import com.ruoyi.system.service.SysMonitorService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (SysFirePoint)表服务实现类
 *
 * @author makejava
 * @since 2022-12-01 16:50:06
 */
@Service("sysFirePointService")
public class SysFirePointServiceImpl implements SysFirePointService {
    @Resource
    private SysFirePointMapper sysFirePointMapper;
    @Resource
    private KieContainer kieContainer;

    @Autowired
    private Configuration configuration;

    @Autowired
    private DroolsConfig droolsConfig;

    @Resource
    private SysMonitorService sysMonitorService;

    public static final String FileName = "/SysFirePoint.drl";
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SysFirePoint queryById(Integer id) {
        return this.sysFirePointMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param sysFirePoint 筛选条件
     * @return 查询结果
     */
    @Override
    public List<SysFirePoint> queryByPage(SysFirePoint sysFirePoint) {
        return this.sysFirePointMapper.queryAllByLimit(sysFirePoint);
    }

    /**
     * 新增数据
     *
     * @param sysFirePoint 实例对象
     * @return 实例对象
     */
    @Override
    public SysFirePoint insert(SysFirePoint sysFirePoint) {
        this.sysFirePointMapper.insert(sysFirePoint);
        return sysFirePoint;
    }

    /**
     * 修改数据
     *
     * @param sysFirePoint 实例对象
     * @return 实例对象
     */
    @Override
    public SysFirePoint update(SysFirePoint sysFirePoint) {
        this.sysFirePointMapper.update(sysFirePoint);
        return this.queryById(sysFirePoint.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.sysFirePointMapper.deleteById(id) > 0;
    }

    @Override
    public String importExcel(List<SysFirePoint> sysFirePoints, boolean updateSupport, String operName) {
        if (StringUtils.isNull(sysFirePoints) || sysFirePoints.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        sysFirePointMapper.insertBatch(sysFirePoints);
        return "成功";
    }

    public void reload() {
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(FileUtil.readString(droolsConfig.getUrl() + FileName, Charset.forName("utf-8")), ResourceType.DRL);
        Results results = kieHelper.verify();
        if (results.hasMessages(Message.Level.ERROR)) {
            System.out.println(results.getMessages());
            throw new IllegalStateException("### errors ###");
        }
        kieContainer = kieHelper.getKieContainer();
        System.out.println("刷新文件");
    }

    // 生成规则文件
    @Async
    public void createDroolsFile() throws IOException, TemplateException {
        List<SysFirePointVO> sysFirePointVOS = getDate();
        Template template = configuration.getTemplate("SysFirePoint.ftl");
        Map<String,Object> map = new HashMap<>();
        map.put("SysFirePointVOList",sysFirePointVOS);
        FileOutputStream file = new FileOutputStream(droolsConfig.getUrl() + FileName);
        OutputStreamWriter out = new OutputStreamWriter(file, "utf-8");
        template.process(map,out);
        out.close();
        System.out.println("success");
        this.reload();
    }

    public List<SysFirePointVO> getDate() {
        List<SysFirePoint> sysFirePoints = sysFirePointMapper.queryAll();
        List<SysFirePointVO> sysFirePointVOS = new ArrayList<>();
        for (SysFirePoint i : sysFirePoints) {
            SysFirePointVO sysDangerPointVO = new SysFirePointVO();
            sysDangerPointVO.setAlert(0);
            sysFirePointVOS.add(sysDangerPointVO);
        }
        return sysFirePointVOS;
    }

    // 定时查询实时数据，是否达到报警条件
    @Scheduled(cron = "0/60 * * * * ?")
    public void ScheduledDataAlert() {
        List<SysFirePointVO> sysFirePointVOS = getDate();
        Map<String, Object> map = ExampleBase.toResult();
        if (CollUtil.isNotEmpty(map)) {
            sysFirePointVOS.forEach(i -> {
                Object o = map.get(i.getBitNumber());
                if (o!=null && !StringUtils.isEmpty(o.toString())) {
                    i.setAv(o.toString());
                    // 调用规则引擎判断
                    KieSession kieSession = kieContainer.newKieSession();
                    kieSession.insert(i);
                    kieSession.fireAllRules();
                    kieSession.dispose();
                    if (i.getAlert() == 1) {
                        SysMonitor query = sysMonitorService.queryByDataBase(i.getBitNumber());
                        if (query == null || !StringUtils.isEmpty(query.getMonitorEndTime())) {
                            if (query != null) {
                                if (!query.getMonitorLevel().equals(i.getAlertType())) {
                                    query.setMonitorEndTime(DateUtil.now());
                                    query.setMonitorState("已恢复");
                                    sysMonitorService.update(query);
                                }
                            }
                            SysMonitor sysMonitor = new SysMonitor();
                            sysMonitor.setMonitorType("火灾报警");
                            sysMonitor.setMonitorName(i.getInstallAddress());
                            sysMonitor.setRealTimeDataAddress(i.getBitNumber());
                            sysMonitor.setMonitorParam("");
                            sysMonitor.setMonitorLevel(i.getAlertType());
                            sysMonitor.setMonitorValue(i.getAv());
                            sysMonitor.setMonitorConfirmState("未确认");
                            sysMonitor.setMonitorState("未恢复");
                            sysMonitor.setMonitorStartTime(DateUtil.now());
                            sysMonitorService.insert(sysMonitor);
                        }
                    } else {
                        SysMonitor query = sysMonitorService.queryByDataBase(i.getBitNumber());
                        if (query != null && StringUtils.isEmpty(query.getMonitorEndTime())) {
                            query.setMonitorEndTime(DateUtil.now());
                            query.setMonitorState("已恢复");
                            sysMonitorService.update(query);
                        }
                    }
                }
            });
        }
    }
}
